/**
 * 账号设置页面脚本
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化侧边栏导航
    initSettingsNav();
    
    // 初始化表单验证
    initFormValidation();
    
    // 初始化密码强度检测
    initPasswordStrength();
    
    // 初始化密码显示/隐藏切换
    initPasswordToggle();
    
    // 初始化头像上传
    initAvatarUpload();
    
    // 初始化注销账号确认
    initDeleteAccount();
});

/**
 * 初始化设置导航
 */
function initSettingsNav() {
    const navItems = document.querySelectorAll('.settings-nav-item');
    const panels = document.querySelectorAll('.settings-panel');
    
    // 处理URL哈希变化
    function handleHashChange() {
        const hash = window.location.hash || '#profile';
        const targetTab = hash.substring(1); // 移除 # 符号
        
        // 激活对应的导航项
        navItems.forEach(item => {
            if (item.getAttribute('data-tab') === targetTab) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        });
        
        // 显示对应的面板
        panels.forEach(panel => {
            if (panel.id === `${targetTab}-panel`) {
                panel.classList.add('active');
            } else {
                panel.classList.remove('active');
            }
        });
    }
    
    // 初始处理哈希
    handleHashChange();
    
    // 监听哈希变化
    window.addEventListener('hashchange', handleHashChange);
    
    // 点击导航项
    navItems.forEach(item => {
        item.addEventListener('click', function(e) {
            const tab = this.getAttribute('data-tab');
            window.location.hash = tab;
            e.preventDefault();
        });
    });
}

/**
 * 初始化表单验证
 */
function initFormValidation() {
    // 个人资料表单
    const profileForm = document.getElementById('profile-form');
    if (profileForm) {
        profileForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 验证表单
            if (validateProfileForm()) {
                // 模拟表单提交
                showToast('个人资料更新成功');
                
                // 实际项目中这里应该发送AJAX请求
                // saveProfile();
            }
        });
    }
    
    // 密码表单
    const passwordForm = document.getElementById('password-form');
    if (passwordForm) {
        passwordForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 验证表单
            if (validatePasswordForm()) {
                // 模拟表单提交
                showToast('密码更新成功');
                
                // 实际项目中这里应该发送AJAX请求
                // updatePassword();
                
                // 重置表单
                this.reset();
                resetPasswordStrength();
            }
        });
    }
}

/**
 * 验证个人资料表单
 */
function validateProfileForm() {
    const fullname = document.getElementById('fullname');
    const email = document.getElementById('email');
    
    let isValid = true;
    
    // 验证姓名
    if (!fullname.value.trim()) {
        showError(fullname, '请输入姓名');
        isValid = false;
    } else {
        clearError(fullname);
    }
    
    // 验证邮箱
    if (!email.value.trim()) {
        showError(email, '请输入邮箱');
        isValid = false;
    } else if (!isValidEmail(email.value)) {
        showError(email, '请输入有效的邮箱地址');
        isValid = false;
    } else {
        clearError(email);
    }
    
    return isValid;
}

/**
 * 验证密码表单
 */
function validatePasswordForm() {
    const currentPassword = document.getElementById('current-password');
    const newPassword = document.getElementById('new-password');
    const confirmPassword = document.getElementById('confirm-password');
    
    let isValid = true;
    
    // 验证当前密码
    if (!currentPassword.value) {
        showError(currentPassword, '请输入当前密码');
        isValid = false;
    } else {
        clearError(currentPassword);
    }
    
    // 验证新密码
    if (!newPassword.value) {
        showError(newPassword, '请输入新密码');
        isValid = false;
    } else if (newPassword.value.length < 8) {
        showError(newPassword, '密码长度至少为8位');
        isValid = false;
    } else {
        clearError(newPassword);
    }
    
    // 验证确认密码
    if (!confirmPassword.value) {
        showError(confirmPassword, '请确认新密码');
        isValid = false;
    } else if (confirmPassword.value !== newPassword.value) {
        showError(confirmPassword, '两次输入的密码不一致');
        isValid = false;
    } else {
        clearError(confirmPassword);
    }
    
    return isValid;
}

/**
 * 显示表单错误
 */
function showError(input, message) {
    const formGroup = input.closest('.form-group');
    let errorElement = formGroup.querySelector('.error-message');
    
    if (!errorElement) {
        errorElement = document.createElement('div');
        errorElement.className = 'error-message';
        formGroup.appendChild(errorElement);
    }
    
    errorElement.textContent = message;
    formGroup.classList.add('has-error');
}

/**
 * 清除表单错误
 */
function clearError(input) {
    const formGroup = input.closest('.form-group');
    const errorElement = formGroup.querySelector('.error-message');
    
    if (errorElement) {
        errorElement.remove();
    }
    
    formGroup.classList.remove('has-error');
}

/**
 * 验证邮箱格式
 */
function isValidEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

/**
 * 初始化密码强度检测
 */
function initPasswordStrength() {
    const newPassword = document.getElementById('new-password');
    if (!newPassword) return;
    
    newPassword.addEventListener('input', function() {
        updatePasswordStrength(this.value);
    });
}

/**
 * 更新密码强度指示器
 */
function updatePasswordStrength(password) {
    const strengthMeter = document.querySelector('.strength-meter');
    const strengthText = document.querySelector('.strength-text');
    
    if (!strengthMeter || !strengthText) return;
    
    const segments = strengthMeter.querySelectorAll('.strength-segment');
    
    // 重置所有段
    segments.forEach(segment => {
        segment.style.backgroundColor = '';
    });
    
    if (!password) {
        strengthText.textContent = '密码强度：无';
        strengthText.style.color = '';
        return;
    }
    
    // 计算密码强度
    let strength = 0;
    
    // 长度检查
    if (password.length >= 8) strength += 1;
    if (password.length >= 12) strength += 1;
    
    // 复杂性检查
    if (/[0-9]/.test(password)) strength += 1;
    if (/[a-z]/.test(password)) strength += 1;
    if (/[A-Z]/.test(password)) strength += 1;
    if (/[^a-zA-Z0-9]/.test(password)) strength += 1;
    
    // 设置强度级别
    let level = 0;
    let color = '';
    let text = '';
    
    if (strength <= 2) {
        level = 1;
        color = 'var(--color-danger)';
        text = '弱';
    } else if (strength <= 4) {
        level = 2;
        color = 'var(--color-warning)';
        text = '中等';
    } else if (strength <= 6) {
        level = 3;
        color = 'var(--color-success)';
        text = '强';
    } else {
        level = 4;
        color = 'var(--color-primary)';
        text = '非常强';
    }
    
    // 更新视觉指示器
    for (let i = 0; i < level; i++) {
        if (segments[i]) {
            segments[i].style.backgroundColor = color;
        }
    }
    
    // 更新文本
    strengthText.textContent = `密码强度：${text}`;
    strengthText.style.color = color;
}

/**
 * 重置密码强度指示器
 */
function resetPasswordStrength() {
    const strengthMeter = document.querySelector('.strength-meter');
    const strengthText = document.querySelector('.strength-text');
    
    if (!strengthMeter || !strengthText) return;
    
    const segments = strengthMeter.querySelectorAll('.strength-segment');
    
    // 重置所有段
    segments.forEach(segment => {
        segment.style.backgroundColor = '';
    });
    
    strengthText.textContent = '密码强度：无';
    strengthText.style.color = '';
}

/**
 * 初始化密码显示/隐藏切换
 */
function initPasswordToggle() {
    const toggleButtons = document.querySelectorAll('.password-toggle');
    
    toggleButtons.forEach(button => {
        button.addEventListener('click', function() {
            const input = this.parentElement.querySelector('input');
            const img = this.querySelector('img');
            
            if (input.type === 'password') {
                input.type = 'text';
                img.src = 'images/icon-eye-off.svg';
                img.alt = '隐藏密码';
            } else {
                input.type = 'password';
                img.src = 'images/icon-eye.svg';
                img.alt = '显示密码';
            }
        });
    });
}

/**
 * 初始化头像上传
 */
function initAvatarUpload() {
    const uploadBtn = document.getElementById('upload-avatar-btn');
    const removeBtn = document.getElementById('remove-avatar-btn');
    const preview = document.getElementById('avatar-preview');
    
    if (!uploadBtn || !removeBtn || !preview) return;
    
    // 上传头像
    uploadBtn.addEventListener('click', function() {
        // 创建文件输入元素
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = 'image/*';
        fileInput.style.display = 'none';
        document.body.appendChild(fileInput);
        
        // 监听文件选择
        fileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const file = this.files[0];
                
                // 检查文件大小
                if (file.size > 2 * 1024 * 1024) {
                    showToast('图片大小不能超过2MB', 'error');
                    return;
                }
                
                // 预览图片
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                };
                reader.readAsDataURL(file);
                
                // 实际项目中这里应该上传图片
                // uploadAvatar(file);
                
                showToast('头像上传成功');
            }
            
            // 移除临时元素
            document.body.removeChild(fileInput);
        });
        
        // 触发文件选择
        fileInput.click();
    });
    
    // 移除头像
    removeBtn.addEventListener('click', function() {
        // 恢复默认头像
        preview.src = 'images/avatar-placeholder.jpg';
        
        // 实际项目中这里应该删除头像
        // removeAvatar();
        
        showToast('头像已移除');
    });
}

/**
 * 初始化注销账号确认
 */
function initDeleteAccount() {
    const confirmCheckbox = document.getElementById('confirm-delete');
    const deleteBtn = document.getElementById('delete-account-btn');
    
    if (!confirmCheckbox || !deleteBtn) return;
    
    // 监听确认框变化
    confirmCheckbox.addEventListener('change', function() {
        deleteBtn.disabled = !this.checked;
    });
    
    // 监听删除按钮点击
    deleteBtn.addEventListener('click', function() {
        if (confirmCheckbox.checked) {
            // 显示确认对话框
            if (confirm('您确定要永久注销账号吗？此操作不可撤销。')) {
                // 实际项目中这里应该发送注销请求
                // deleteAccount();
                
                showToast('账号已注销，即将退出...', 'warning');
                
                // 模拟跳转
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 3000);
            }
        }
    });
}

/**
 * 显示提示消息
 */
function showToast(message, type = 'success') {
    // 检查是否已存在Toast容器
    let toastContainer = document.querySelector('.toast-container');
    
    if (!toastContainer) {
        // 创建Toast容器
        toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container';
        document.body.appendChild(toastContainer);
    }
    
    // 创建Toast元素
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    
    // 添加到容器
    toastContainer.appendChild(toast);
    
    // 显示动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    // 自动关闭
    setTimeout(() => {
        toast.classList.remove('show');
        
        // 移除元素
        setTimeout(() => {
            toastContainer.removeChild(toast);
            
            // 如果没有更多Toast，移除容器
            if (toastContainer.children.length === 0) {
                document.body.removeChild(toastContainer);
            }
        }, 300);
    }, 3000);
}

/**
 * 移动端菜单切换
 */
document.addEventListener('DOMContentLoaded', function() {
    const mobileMenuToggle = document.querySelector('.mobile-menu-toggle');
    const mainNav = document.querySelector('.main-nav');
    
    if (mobileMenuToggle && mainNav) {
        mobileMenuToggle.addEventListener('click', function() {
            this.classList.toggle('active');
            mainNav.classList.toggle('active');
        });
    }
    
    // 用户下拉菜单
    const userDropdownToggle = document.querySelector('.user-dropdown-toggle');
    const userDropdownMenu = document.querySelector('.user-dropdown-menu');
    
    if (userDropdownToggle && userDropdownMenu) {
        userDropdownToggle.addEventListener('click', function(e) {
            e.stopPropagation();
            userDropdownMenu.classList.toggle('active');
        });
        
        // 点击其他区域关闭下拉菜单
        document.addEventListener('click', function() {
            userDropdownMenu.classList.remove('active');
        });
        
        userDropdownMenu.addEventListener('click', function(e) {
            e.stopPropagation();
        });
    }
});